<template>
    <div id="cart">
        <van-nav-bar
                title="购物车"
                left-arrow
                class="my-nav"
                :fixed="true"
                right-text="编辑"
                @click-left="onClickLeft"
                @click-right="onClickRight"
        />
        <div style="margin-top: 50px;margin-bottom: 50px;background: #fff">
            <div v-if="carts.length>0" class="goods-list" v-for="cart in carts" :key="cart.id">
                <div class="shop"
                     style="border-bottom: 1px solid #eee; height: 25px; line-height: 25px; font-weight: 500;padding: 10px">
                    <div @click="onCheckedShopCart(cart)">
                        <van-checkbox style="float: left" :value="cart.checkedArray.length===cart.commodity.length"/>
                    </div>
                    &nbsp;&nbsp;&nbsp;
                    <van-icon name="shop" style="color: red;font-weight: 900;font-size: 18px"/>
                    {{cart.name}}
                </div>
                <van-checkbox-group class="card-goods" v-model="cart.checkedArray">
                    <div v-for="item in cart.commodity" :key="item.skuId">
                        <van-checkbox
                                class="card-goods__item"
                                :key="item.skuId"
                                :name="item.skuId"
                        />
                        <van-card
                                :title="item.title"
                                :desc="item.standard+'/'+item.color"
                                :price="formatPrice(item.price)"
                                :thumb="item.thumb"
                                :thumb-link="'/#/goods/'+item.goodsId">
                            <div slot="footer">
                                <van-stepper v-model="item.count" :max="item.stepperLimit" @change="onChangeBuyCount(item)"/>
                            </div>
                        </van-card>
                    </div>
                </van-checkbox-group>
            </div>
            <div v-if="carts.length===0" style=" height: 100px;margin: 0 auto; text-align: center;padding: 20px; color: #666">
                购物车中空空如也!
                <br><br>
                <van-button size="small" @click="$router.push('/classification')">去逛逛</van-button>
            </div>
        </div>
        <template v-if="carts.length>0">
        <div v-if="showBuyBar">
            <van-submit-bar
                    :price="totalPrice"
                    :disabled="!totalPrice"
                    :button-text="submitBarText"
                    @submit="onSubmit"
            >
                <div @click="onCheckedAll">
                    <van-checkbox :value="checkedAll" style="margin-left: 12px;">全选</van-checkbox>
                </div>
            </van-submit-bar>
        </div>
        <div v-else>
            <van-submit-bar
                    :disabled="!totalPrice"
                    :button-text="deleteBarText"
                    @submit="onDeleteSubmit"
            >
                <div @click="onCheckedAll">
                    <van-checkbox :value="checkedAll" style="margin-left: 12px;">全选</van-checkbox>
                </div>
            </van-submit-bar>
        </div>
        </template>
        <template v-else>
            <div class="not-show-bar" style="height: 50px;bottom: 0;background: #fff"></div>
        </template>
    </div>
</template>

<script>
  import {listCurrentUserCart,save,deleteCartAll} from '../../api/carts'
  import { Dialog } from 'vant';
  import bus from  '../../bus'

  import {
    Toast
  } from 'vant';

  export default {
    data() {
      return {
        showBuyBar: true,
        checkedAll: false,
        carts: [/*{
          "id": 11,
          "name": "山东金怡华通讯",
          "commodity": [
            {
              checked: false,
              "title": "华为畅享8",
              "standard": "4+64/全网通",
              "color": "金色",
              "count": 4,
              "price": 1085,
              "thumb": "http://image-jinyijia1688-com.oss-cn-beijing.aliyuncs.com/goods_f4c9a76aee24e8176139b51fa2d91f6a.jpg",
              "skuCode": "2611200778",
              "shopId": 11,
              "skuId": 3673
            }
          ]
        }*/]
      };
    },
    computed: {
      submitBarText() {
        let list = this.listCheckedSku();
        const count = list.reduce((total, item) => total + item.count, 0);
        return '结算' + (count ? `(${count})` : '');
      },
      deleteBarText (){
        let list = this.listCheckedSku();
        const count = list.reduce((total, item) => total + item.count, 0);
        return '删除' + (count ? `(${count})` : '');
      },
      totalPrice() {
        let list = this.listCheckedSku();
        return list.reduce((total, item) => total +  item.price * item.count, 0) * 100;
      }
    },
    watch: {
      carts: {
        handler(newValue){
          const isCheckedAll = () => {
            for(let cart of newValue){
              if(cart.checkedArray.length!==cart.commodity.length){
                return false;
              }
            }
            return true;
          };
          if (isCheckedAll()) {
            this.checkedAll = true;
          } else {
            this.checkedAll = false;
          }
        },
        deep: true
      }
    },
    methods: {

      formatPrice(price) {
        return (price).toFixed(2);
      },
      onSubmit() {
        let cartsCopy = JSON.parse(JSON.stringify(this.carts));
        let checkedSkuIdSet = new Set();
        this.carts.forEach(cart => {
          cart.checkedArray.forEach(skuId => checkedSkuIdSet.add(skuId));
        });
        cartsCopy = cartsCopy.map(cart=>{
          let commodity = cart.commodity;
          cart.commodity = commodity.filter(item=>checkedSkuIdSet.has(item.skuId));
          return cart;
        }).filter(cart=>cart.commodity.length>0);
        bus.state.buyList = cartsCopy;
        this.$router.push('/order-submit');
//        Toast('点击结算');
      },
      onDeleteSubmit (){
        Dialog.confirm({
          message: '是否确认删除?'
        }).then(() => {
          deleteCartAll(this.listCheckedSku().map(item=>({
            shopId: item.shopId,
            skuCode: item.skuCode
          })),_=>{
            Toast('删除成功');
            listCurrentUserCart(data => {
              this.carts = data;
            })
          })
        }).catch(() => {
          Toast('取消成功');
        });

      },
      listCheckedSku(){
        let list = [];
        let checkedSkuIdSet = new Set();
        this.carts.forEach(cart => {
          cart.checkedArray.forEach(skuId => checkedSkuIdSet.add(skuId));
          cart.commodity.forEach(item => list.push(item));
        });
        return list.filter(item=>checkedSkuIdSet.has(item.skuId));
      },
      onClickLeft() {
        this.$router.back(-1)
      },
      onClickRight() {
        this.showBuyBar=!this.showBuyBar;
      },
      onCheckedAll (){
        this.checkedAll = !this.checkedAll;
        if (this.checkedAll) {
          this.carts.forEach(cart => {
            cart.checked = false;
            this.onCheckedShopCart(cart)
          })
        }else{
          this.carts.forEach(cart => {
            cart.checked = true;
            this.onCheckedShopCart(cart)
          })
        }
      },
      onCheckedShopCart(cart) {
        cart.checked = !cart.checked;
        if (cart.checkedArray.length > 0) {
          cart.checkedArray.splice(0, cart.checkedArray.length)
        }
        if (cart.checked) {
          cart.commodity.forEach(item => cart.checkedArray.push(item.skuId))
        }
      },
      onChangeBuyCount (sku){
        let cart = {
          shopId:sku.shopId,
          skuCode: sku.skuCode,
          number: sku.count,
          skuId: sku.skuId
        }
        save(cart,d=>{})
      }
    },
    mounted() {
      listCurrentUserCart(data => {
        this.carts = data;
      })
    }
  };
</script>

<style lang="less" scoped>
    .goods-list {
        /*border-bottom: 5px solid #fafafa;*/
        /* box-shadow: 5px 5px 5px #ddd;*/
        box-shadow: 2px 2px 1px #f2f2f2;
    }

    .card-goods {
        padding: 10px;
        color: #666;
        font-size: 17px;
        /*background-color: #fff;*/

        &__item {
            position: relative;
            float: left;
            align-items: center;
            background-color: #fafafa;
            margin-top: 40px;

            .van-checkbox__label {
                width: 100%;
                padding: 0 10px 0 15px;
                box-sizing: border-box;
            }

            .van-checkbox__icon {
                top: 50%;
                left: 10px;
                z-index: 1;
                position: absolute;
                margin-top: -10px;
            }

            .van-card__price {
                color: #f44;
            }

        }
    }

    .van-submit-bar, .not-show-bar {
        left: 0;
        /*bottom: 50px;*/
        width: 100%;
        z-index: 100;
        position: fixed;
    }

</style>
